package com.example.chatplatform.controller;

import com.example.chatplatform.model.dto.AlterPasswordDTO;
import com.example.chatplatform.model.dto.RegisterDTO;
import com.example.chatplatform.model.entity.User;
import com.example.chatplatform.model.vo.CronyInfoVO;
import com.example.chatplatform.model.vo.GroupInfoVO;
import com.example.chatplatform.model.vo.UserDetailVO;
import com.example.chatplatform.result.Result;
import com.example.chatplatform.service.FileOssService;
import com.example.chatplatform.service.UserService;
import com.example.chatplatform.util.JwtUtil;
import com.example.chatplatform.ws.ChatEndpoint;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public UserService userService;

    @Autowired
    public FileOssService fileOssService;

    @Autowired
    public ChatEndpoint chatEndpoint;

    //用户注册
    @PostMapping("/userRegister")
    private Result userRegister(@RequestParam("avatar") MultipartFile file, @RequestParam("user") String userJson) throws JsonProcessingException {
        User user = new ObjectMapper().readValue(userJson, User.class);
        Integer userId = userService.user(user);
        if(userId == null) {
            String FileUrl = fileOssService.uploadToOss(file);
            Integer userId1 = userService.userRegister(user, FileUrl);
            if(userId1 == null){
                return Result.error("注册失败");
            } else {
                return Result.success("注册成功");
            }
        } else {
            return Result.error("已有该账号");
        }
    }

    //用户登录
    @PostMapping("/userLogin")
    private Result userLogin(@RequestBody User user, HttpSession session) {
        User user1  = userService.userLogin(user.getUserAccount(), user.getUserPassword());
        if(user1 == null){
            return Result.error("账号或密码错误");
        } else {
            if (!chatEndpoint.onlineUser(user1.getUserId())) {
                session.setAttribute("userId", user1.getUserId());
                user1.setToken(JwtUtil.createToken(user1.getUserAccount()));
                return Result.success(user1);
            } else {
                return Result.error("该用户已登录");
            }
        }
    }

    //验证token
    @GetMapping("/checkToken/{token}")
    public Boolean checkToken(@PathVariable String token){
        return JwtUtil.checkToken(token);
    }

    //查询用户信息
    @GetMapping("/userInfo")
    private Result userInfo(@RequestParam Integer userId) {
        User user = userService.userInfo(userId);
        if (user != null) {
            return Result.success(user);
        } else {
            return Result.error("查询失败");
        }
    }

    //修改用户信息(不包括头像)
    @PatchMapping("/alterUser")
    private Result alterUser(@RequestBody User user) {
        if (userService.alterUser(user)) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    //修改用户信息
    @PatchMapping("/alterUserWithAvatar")
    private Result alterUserWithAvatar(@RequestParam("avayar") MultipartFile file, @RequestParam("user") String userJson) throws JsonProcessingException {
        User user = new ObjectMapper().readValue(userJson, User.class);
        String userAvatar = userService.avatar(user.getUserId());
        if (userAvatar != null) {
            if (fileOssService.deleteFileFromOss(userAvatar)) {
                System.out.println("已删除" + userAvatar);
                String FileUrl = fileOssService.uploadToOss(file);
                System.out.println(FileUrl);
                if (userService.alterUserWithAvatar(user, FileUrl)) {
                    return Result.success("修改成功");
                } else {
                    return Result.error("修改失败");
                }
            } else {
                return Result.error("修改失败");
            }
        } else {
            String FileUrl = fileOssService.uploadToOss(file);
            if (userService.alterUserWithAvatar(user, FileUrl)) {
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        }
    }

    //修改密码
    @PatchMapping("/alterPassword")
    private Result alterPassword(@RequestBody AlterPasswordDTO alterPasswordDTO) {
        int i =  userService.alterPassword(alterPasswordDTO);
        if (i == 1) {
            return Result.success("修改成功");
        } else if (i == 2){
            return Result.error("原密码错误");
        } else {
            return Result.error("修改失败");
        }
    }

    //注销用户
    @DeleteMapping("/deleteUser")
    private Result deleteUser(@RequestParam Integer userId) {
        String userAvatar = userService.avatar(userId);
        String deleteUserAvatar = "https://syhsyh.oss-cn-chengdu.aliyuncs.com/kongfeilong/c6c426fdb8214f219e2ab7592a177d75.jpg";
        if (userService.deleteUser(userId, deleteUserAvatar) && fileOssService.deleteFileFromOss(userAvatar)) {
            return Result.success("注销成功");
        } else {
            return Result.error("注销失败");
        }
    }

    //查询用户的好友和群聊
    @GetMapping("/getObjectList")
    private Result getObjectList(@RequestParam Integer userId, @RequestParam String currentType) {
        List getbjectS = userService.getObjectList(userId, currentType);
        if (getbjectS != null) {
            return Result.success(getbjectS);
        } else {
            return Result.error("查询失败");
        }
    }

    //搜索所有用户和群聊
    @GetMapping("/searchObject")
    private Result searchObject(@RequestParam String currentType, @RequestParam String searchObjectValue) {
        List searchObjectS = userService.searchObject(currentType, searchObjectValue);
        if (searchObjectS != null) {
            return Result.success(searchObjectS);
        } else {
            return Result.error("查询失败");
        }
    }

    //查询用户或好友的详情信息
    @GetMapping("/getUserInfo")
    private Result getUserInfo(@RequestParam Integer userId, @RequestParam Integer cronyId) {
        UserDetailVO userDetailVO = userService.getUserInfo(userId, cronyId);
        if (userDetailVO != null) {
            return Result.success(userDetailVO);
        } else {
            return Result.error("查询失败");
        }
    }

}
